import { FC, useEffect, useState } from "react"
import { AtForm, AtIcon } from 'taro-ui'
import { Picker } from '@tarojs/components'
import ZInput from "../ZInput"
import { AtButton,AtToast  } from 'taro-ui'
import "taro-ui/dist/style/components/button.scss";
import "taro-ui/dist/style/components/loading.scss";
import "taro-ui/dist/style/components/list.scss";
import { View } from "@tarojs/components";
import style from './index.module.scss'
//校验  validator
import "@/validator/Login/index.ts"
import Validator from 'validatorjs';

import { handleError } from "@/util/errorHandler"
type fieldType = {
    name: string,
    placerholder: string,
    lefticon: string,
    readonly?: boolean,
    Verification?: boolean
}

type VerificationsType = {
    type: string,
    name: string,
    rules?:Array<{[key:string]:string}>
    validatorMsg?:Array<{[key:string]:string}>
    container: Array<fieldType>
}

type ZloginType = {
    //判断是否开启选择器
    listFlag?: boolean,
    fields: Array<VerificationsType>,
    onSubmit: (data: { [key: string]: any }) => void
}


const Zlogin: FC<ZloginType> = (props) => {
    const { fields, onSubmit, listFlag = false } = props
    const [formData, setFormData] = useState<{ [key: string]: string }>({})
    //选择的登录类型
    let [selectType, setSelectType] = useState(fields[0].name)
    //选择的登录的规则
    let [selectRules, setSelectRules] = useState(fields[0].rules)
    //选择的登录的规则
    let [selectRulesMsg, setSelectRulesMsg] = useState(fields[0].validatorMsg)
    //指定登录类型下的表单
    let [selectVerification, setSelectVerification] = useState<Array<fieldType>>(fields[0].container)
    //获取选择器类型
    const selector = fields.map((item) => {
        const { name } = item
        return name
    })
    
    //修改选择器类型
    const onChange = (e) => {
        setSelectType(selector[e.detail.value])
    }
    //监听登录方式的改变
    useEffect(()=>{
        const selectValue = fields.filter((item)=>item.name === selectType) 
        //清空表单数据
        const initialFormData = selectValue[0].container.reduce((acc, item) => {
            acc[item.name] = '';
            return acc;
        }, {});
        setFormData(initialFormData);
        setSelectRules(selectValue[0].rules)
        setSelectRulesMsg(selectValue[0].validatorMsg)
        setSelectVerification(selectValue[0].container)
    },[selectType])


    const handleChange = (field: string, value: string) => {
        setFormData({
            ...formData,
            [field]: value
        })
    }

    const handleSubmit = () => {
        console.log('formData',formData)
        const validation = new Validator(formData, selectRules,selectRulesMsg);
        if (validation.fails()) {
            const errdatas = validation.errors.all()
            let errdata:string[] = []
            for(let key in errdatas){
                errdata.push(errdatas[key][0])
            }
            const err = JSON.stringify(errdata.join(','))
            handleError({message:err})
          } else {
            onSubmit(formData)
          }
    }


    return <AtForm>
        {
            selectVerification.map((item, index) => {
                const { name, placerholder, lefticon, Verification = false } = item
                return <View className={style['ZAtForm']} key={index}>
                    {listFlag && index == 0 ?
                        <View className={style['left_picker']}>
                            <Picker mode='selector' range={selector} onChange={onChange}>
                               <View className={style['picker_box']}>
                                    <View className={style['title']}>{selectType}</View>
                                    <AtIcon prefixClass='fa' value='angle-double-down' size='16'></AtIcon>
                               </View>
                            </Picker>
                        </View>
                        : null}
                    <ZInput
                        required = {true}
                        name={name}
                        value={formData[name]}
                        setValue={(value) => handleChange(name, value)}
                        placeholder={placerholder}
                        lefticon={lefticon}
                    >
                        {Verification ? <>
                            <View style={{ fontSize: '12px' }}>图形验证码</View>
                        </> : null}
                    </ZInput>

                </View>
            })
        }

        <AtButton size='small'   onClick={handleSubmit}>提交</AtButton>
    </AtForm>
}

export default Zlogin